#include "DesktopTimer.h"
#include "log.h"
#include "appsingleton.hpp"
#include <QHBoxLayout>
#include <QScreen>
#include <QStackedLayout>
#include <QListWidget>
#include <QGuiApplication>
#include <QVBoxLayout>
#include <QColorDialog>
#include <QRegion>
#include "qtmaterialtabs.h"
#include "qtmaterialflatbutton.h"
#include "qtmaterialdialog.h"
#include "TimedWidget.h"
#include "ReminderWidget.h"
#include "SystemWidget.h"
#include <QStackedWidget>
#include "RoundTimeBar.h"
#include "DigitalClock.h"
#include "DateLCD.h"
#include "WeekdayDisplay.h"
#include "SettingWidget.h"
#include "PlanWidget.h"
#include "TaskPanelController.h"
#include "ScreenshotWidget.h"
#include "ScreenshotService.h"
#include "ConfigService.h"
#include "SoundService.h"
#include "QuoteService.h"
#include "StyleLoader.h"
#include <QMessageBox>
#include <QThread>
#include <QTimer>
#include <QClipboard>
#include <QFileDialog>
#include <QPropertyAnimation>
#include <QMenu>
#include <QAction>
#include <QApplication>
#include <QGraphicsDropShadowEffect>
#include <QFrame>
#include <QVBoxLayout>

constexpr int TITLE_BAR_H = 48;
const QString APP_NAME = QObject::tr("计时助手");

int DesktopTimer::getScreenWidth() const
{
    return m_nScreenWidth;
}

void DesktopTimer::setScreenWidth(int width)
{
    m_nScreenWidth=width;
}

int DesktopTimer::getScreenHeight() const
{
    return m_nScreenHeigth;
}

void DesktopTimer::setScreenHeigth(int heigth)
{
    m_nScreenHeigth = heigth;
}

void DesktopTimer::resizeEvent(QResizeEvent *event)
{
    setWindowStyle();
    update();
    QWidget::resizeEvent(event);
}


DesktopTimer::DesktopTimer(QWidget *parent)
    :FramelessWindow(parent)
    ,m_bTitleShow(true)
    ,m_pScreenshotWidget(nullptr)
    ,m_bSound(true)
    ,m_bPinned(false)
{
    // [FDD-2025-03-015] 初始化任务面板控制器
    m_taskPanelCtrl = new TaskPanelController(this);
    
    // 创建嵌入的 PlanWidget
    m_embeddedPlanWidget = new PlanWidget();
    if (!m_taskPanelCtrl->bindPlanWidget(m_embeddedPlanWidget)) {
        qWarning() << "Failed to bind embedded PlanWidget";
    }
    
    // 注册 TipType 类型
    qRegisterMetaType<TipType>("TipType");
    // 设置窗口样式和背景
    setWindowStyle();
    initForm();
    setTitlebarWidgets({titleWidget, lblIcon, lblTitle});
    // 初始化控件和布局
    initMainLayout();

    initSystemTrayIcon();
    // ✅ 使用ConfigService获取超时动作配置
    setScreenStyle(ConfigService::instance().getTimeoutAction().screenAction);

    connectFunction();
    
    // 加载统一样式
    applyStyles();
    
    // [FDD-2025-03-015][UX] 默认启动时展开任务列表，稍后由持久化状态覆盖
    toggleTaskPanel(true);

    // [FDD-2025-03-015][AC-003] 恢复上次的展开状态（延迟执行）
    QTimer::singleShot(100, this, [this]() {
        connect(m_taskPanelCtrl, &TaskPanelController::stateChanged,
                this, [this](bool expanded) {
            toggleTaskPanel(expanded);
        });
        m_taskPanelCtrl->restoreState();
    });
}

DesktopTimer::~DesktopTimer()
{
    roundTimeBarThread->quit();
    roundTimeBarThread->wait();
    delete roundTimeBarThread;

    if(roundTimeBar){
        delete roundTimeBar;
        roundTimeBar =nullptr;
    }
    if(m_pScreenshotWidget){
        // 先隐藏并处理所有事件，确保不会在析构时触发 paintEvent
        m_pScreenshotWidget->hide();
        QApplication::processEvents();
        delete m_pScreenshotWidget;
        m_pScreenshotWidget = nullptr;
    }
    if(m_pDate){
        delete m_pDate;
        m_pDate = nullptr;
    }
}

void DesktopTimer::closeEvent(QCloseEvent *event)
{
    if (m_pSysIcon->isVisible())
    {
        this->hide();
        m_pSysIcon->showMessage(APP_NAME, "小主，我已躲进托盘里面了，请在托盘里找我哦！", QSystemTrayIcon::Information,3000);
        event->ignore();
    }
    else {
        event->accept();
    }
}


void DesktopTimer::changeEvent(QEvent *event)
{
    if ( event->type() == QEvent::WindowStateChange ) {
        if ( this->windowState().testFlag(Qt::WindowMaximized) ) {
            btnMax->setProperty("maximized", true);
        } else if ( this->windowState().testFlag(Qt::WindowNoState) ) {
            btnMax->setProperty("maximized", false);
        }
        // 强制刷新样式
        btnMax->style()->unpolish(btnMax);
        btnMax->style()->polish(btnMax);
    }
}

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
void DesktopTimer::enterEvent(QEnterEvent *event)
#else
void DesktopTimer::enterEvent(QEvent *event)
#endif
{
    setTitleBarVisible(true);
    QWidget::enterEvent(event); // 调用父类默认
}

void DesktopTimer::leaveEvent(QEvent *event)
{
    setTitleBarVisible(false);
    QWidget::leaveEvent(event); // 调用父类默认实现
}

void DesktopTimer::initForm()
{
    // 1.3 窗体整体采用垂直布局
    QVBoxLayout* vl = new QVBoxLayout(this);
    vl->setSpacing(0);
    vl->setContentsMargins(0, 0, 0, 0);

    // 1.4 并嵌套一层QWidget
    QWidget* frameWidget = new QWidget(this);
    frameWidget->setObjectName("mainFrameWidget");
    vl->addWidget(frameWidget);

    // 1.5 嵌套的QWidget同样采用垂直布局
    QVBoxLayout* layout = new QVBoxLayout(frameWidget);
    layout->setSpacing(0);
    layout->setContentsMargins(0, 0, 0, 0);
    m_mainContainer = layout;

    // 2. 标题栏
    titleWidget = new QWidget(this);
    titleWidget->setObjectName("mainTitleBar");
    titleWidget->setMinimumHeight(0);
    titleWidget->setMaximumHeight(TITLE_BAR_H);
    titleWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);

    // 2.2 标题栏采用水平布局
    QHBoxLayout* titleLayout = new QHBoxLayout(titleWidget);
    titleLayout->setContentsMargins(8, 8, 8, 8);
    titleLayout->setSpacing(0);

    // 2.3 把标题栏添加到整体窗体布局中
    layout->addWidget(titleWidget);

    // 2.4 添加图标
    lblIcon = new QLabel(this);
    lblIcon->setObjectName("mainTitleIcon");
    lblIcon->setFixedSize(20, 20);
    titleLayout->addWidget(lblIcon);

    // 2.5 添加弹簧: 在图标和标题之间增加间距
    QSpacerItem* space = new QSpacerItem(6, 20, QSizePolicy::Fixed, QSizePolicy::Fixed);
    titleLayout->addSpacerItem(space);

    // 2.6 添加标题
    lblTitle = new QLabel(this);
    lblTitle->setObjectName("mainTitleLabel");
    lblTitle->setText(APP_NAME);
    lblTitle->setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
    titleLayout->addWidget(lblTitle);

    // 2.7 添加最小化按钮
    btnMin = new QPushButton(this);
    btnMin->setObjectName("mainBtnMin");
    btnMin->setCursor(QCursor(Qt::PointingHandCursor));
    btnMin->setFixedSize(36, 32);
    titleLayout->addWidget(btnMin);

    // 2.8 添加最大化按钮
    btnMax = new QPushButton(this);
    btnMax->setObjectName("mainBtnMax");
    btnMax->setCursor(QCursor(Qt::PointingHandCursor));
    btnMax->setFixedSize(36, 32);
    titleLayout->addWidget(btnMax);

    // 2.9 添加关闭按钮
    btnClose = new QPushButton(this);
    btnClose->setObjectName("mainBtnClose");
    btnClose->setCursor(QCursor(Qt::PointingHandCursor));
    btnClose->setFixedSize(36, 32);
    titleLayout->addWidget(btnClose);

    // 3. 主体
    mainWidget = new QWidget(this);
    mainWidget->setObjectName("mainContentArea");

    // 3.2 主体采用水平布局
    mainLayout = new QHBoxLayout(mainWidget);
    mainLayout->setSpacing(10);
    mainLayout->setContentsMargins(10, 10, 10, 10);

    // 3.3 把主体添加到整体窗体布局中
    layout->addWidget(mainWidget);
    
    // [FDD-2025-03-015][AC-001] 创建任务面板容器（初始隐藏）
    createTaskPanelHost(layout);
}

/**
 * @brief [FDD-2025-03-015][AC-001] 创建任务面板容器并配置动画
 * @param parentLayout 父布局（frameWidget 的 VBoxLayout）
 */
void DesktopTimer::createTaskPanelHost(QVBoxLayout* parentLayout)
{
    if (!parentLayout) {
        qWarning() << "[TaskPanel] parent layout missing";
        return;
    }

    m_taskPanelHost = new QFrame(this);
    m_taskPanelHost->setObjectName("taskPanelHost");
    m_taskPanelHost->setMaximumHeight(0);  // 初始收缩状态
    m_taskPanelHost->setMinimumHeight(0);
    m_taskPanelHost->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    m_taskPanelHost->setVisible(false);
    
    // 应用深色主题样式
    m_taskPanelHost->setStyleSheet(
        "QFrame#taskPanelHost { "
        "  background-color: #2b2b2b; "
        "  border-top: 1px solid #3c3c3c; "
        "}"
    );
    
    // 将嵌入的 PlanWidget 放入容器
    QVBoxLayout* hostLayout = new QVBoxLayout(m_taskPanelHost);
    hostLayout->setContentsMargins(0, 0, 0, 0);
    hostLayout->setSpacing(0);
    hostLayout->setSizeConstraint(QLayout::SetMinimumSize);
    if (m_embeddedPlanWidget) {
        m_embeddedPlanWidget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
        hostLayout->addWidget(m_embeddedPlanWidget);
    }

    // 添加到父布局
    parentLayout->addWidget(m_taskPanelHost);
    
    // 配置动画 [AC-001][AC-002]
    m_panelAnimation = new QPropertyAnimation(m_taskPanelHost, "maximumHeight", this);
    m_panelAnimation->setDuration(300);  // P95 ≤ 300ms
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    m_panelAnimation->setEasingCurve(QEasingCurve::OutCubic);
#else
    m_panelAnimation->setEasingCurve(QEasingCurve::Type::OutCubic);
#endif
    connect(m_panelAnimation, &QPropertyAnimation::finished,
            this, &DesktopTimer::onPanelAnimationFinished);
            
    qDebug() << "[TaskPanel] Host created and animation configured";
}

void DesktopTimer::setTitleBarVisible(bool visible)
{
    if (!titleWidget) {
        return;
    }

    if (!m_titleAnimation) {
        m_titleAnimation = new QPropertyAnimation(titleWidget, "maximumHeight", this);
        m_titleAnimation->setDuration(220);
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
        m_titleAnimation->setEasingCurve(QEasingCurve::InOutCubic);
#else
        m_titleAnimation->setEasingCurve(QEasingCurve::Type::InOutCubic);
#endif
        connect(m_titleAnimation, &QPropertyAnimation::finished,
                this, &DesktopTimer::onTitleAnimationFinished);
    }

    if (m_titleTargetVisible == visible &&
        (!m_titleAnimation || m_titleAnimation->state() != QAbstractAnimation::Running)) {
        return;
    }

    m_titleTargetVisible = visible;
    m_titleAnimation->stop();

    titleWidget->setVisible(true);
    titleWidget->setMinimumHeight(0);
    int startHeight = titleWidget->isVisible() ? titleWidget->height() : titleWidget->maximumHeight();
    m_titleAnimation->setStartValue(startHeight);
    m_titleAnimation->setEndValue(visible ? TITLE_BAR_H : 0);
    m_titleAnimation->start();
    refreshLayoutGeometry();
}

void DesktopTimer::onTitleAnimationFinished()
{
    if (!m_titleAnimation || !titleWidget) {
        return;
    }

    const bool finalVisible = m_titleAnimation->endValue().toInt() > 0;
    m_bTitleShow = finalVisible;

    if (!finalVisible) {
        titleWidget->setMaximumHeight(0);
        titleWidget->setVisible(false);
    } else {
        titleWidget->setMaximumHeight(TITLE_BAR_H);
        titleWidget->setVisible(true);
    }

    setWindowStyle();
    refreshLayoutGeometry();
}

void DesktopTimer::initSystemTrayIcon()
{
    // 创建系统托盘图标
    m_pSysIcon = new QSystemTrayIcon(this);
    m_pSysIcon->setIcon(QIcon(":/resource/ico/DesktopTimer.ico"));
    m_pSysIcon->setToolTip(APP_NAME);

    // 创建托盘菜单
    trayMenu = new QMenu(this);
    // 添加菜单项
    settingsAction = new QAction("设置", this);
    muteAction = new QAction("静音", this);  // 初始为"静音"
    unlockAction = new QAction("解除锁定", this);
    unlockAction->setVisible(false);  // 初始隐藏，只在锁定时显示
    refreshAction = new QAction("刷新", this);
    aboutAction = new QAction("关于", this);
    exportDataAction = new QAction("导出数据", this);
    quitAction = new QAction("退出", this);

    // 添加到托盘菜单
    trayMenu->addAction(settingsAction);
    trayMenu->addAction(muteAction);
    trayMenu->addAction(unlockAction);  // 添加解除锁定选项
    trayMenu->addAction(refreshAction);
    trayMenu->addSeparator();
    trayMenu->addAction(aboutAction);
    trayMenu->addAction(exportDataAction);
    trayMenu->addSeparator();
    trayMenu->addAction(quitAction);
    
    // 创建全局快捷键 Alt+Shift+L 切换幽灵模式
    unlockShortcut = new QShortcut(QKeySequence("Alt+Shift+L"), this);
    unlockShortcut->setEnabled(false);  // 初始禁用，只在锁定时启用

    // 设置托盘图标的菜单
    m_pSysIcon->setContextMenu(trayMenu);

    // 双击托盘图标显示窗口
    connect(m_pSysIcon, &QSystemTrayIcon::activated, this, &DesktopTimer::onTrayIconActivated);

    // 连接菜单项的信号和槽
    connect(settingsAction, &QAction::triggered, this, &DesktopTimer::openSettings);
    connect(muteAction, &QAction::triggered, this, &DesktopTimer::toggleMute);
    connect(unlockAction, &QAction::triggered, this, &DesktopTimer::togglePin);  // 解除锁定
    connect(refreshAction, &QAction::triggered, this, &DesktopTimer::updateAllData);
    connect(aboutAction, &QAction::triggered, this, &DesktopTimer::showAboutDialog);
    connect(exportDataAction, &QAction::triggered, this, &DesktopTimer::exportData);
    connect(quitAction, &QAction::triggered, qApp, &QApplication::quit);
    
    // 连接快捷键
    connect(unlockShortcut, &QShortcut::activated, this, &DesktopTimer::togglePin);  // Alt+Shift+L 切换幽灵模式

    // 显示托盘图标
    m_pSysIcon->show();
}

void DesktopTimer::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
    switch (reason) {

    case QSystemTrayIcon::Trigger:
        break;
    case QSystemTrayIcon::DoubleClick:
        this->show();
        break;
    default:
        break;

    }
}

void DesktopTimer::openSettings()
{
    // [FDD-2025-03-021][AC-002] 使用 WindowRegistry 实现单例窗口管理
    showSingletonWindow("settings", []() -> QWidget* {
        SettingWidget* pSetting = new SettingWidget();
        return pSetting;
    });
}

void DesktopTimer::openPlan()
{
    // [FDD-2025-03-021][AC-002] 使用 WindowRegistry 实现单例窗口管理
    QWidget* planWindow = showSingletonWindow("plan", []() -> QWidget* {
        PlanWidget* pPlan = new PlanWidget();
        pPlan->setWindowTitle("日计划 - DesktopTimer");
        pPlan->setMinimumSize(800, 600);

        // 应用与主界面一致的深色主题样式
        QString style = StyleLoader::loadDarkTheme();
        if (!style.isEmpty()) {
            pPlan->setStyleSheet(style);
        }

        // 设置窗口图标
        pPlan->setWindowIcon(QIcon(":/resource/ico/DesktopTimer.ico"));

        return pPlan;
    });

    if (planWindow) {
        logInfo("打开日计划窗口");
    }
}

void DesktopTimer::startScreenshot()
{
    logInfo("开始截图");
    
    // 隐藏主窗口（避免截图中包含自己）
    hide();
    
    // 延迟一下，确保窗口完全隐藏
    QTimer::singleShot(100, [this]() {
        // 创建截图工具
        if (!m_pScreenshotWidget) {
            m_pScreenshotWidget = new ScreenshotWidget();
            connect(m_pScreenshotWidget, &ScreenshotWidget::screenshotFinished,
                    this, [this](const QPixmap& /*pixmap*/) {
                // 完成按钮已经将截图复制到剪贴板了，这里只需要显示主窗口
                // 保存按钮会单独处理保存逻辑（提示用户另存为）
                show();
            });
            
            connect(m_pScreenshotWidget, &ScreenshotWidget::screenshotCancelled,
                    this, [this]() {
                // 截图取消，显示主窗口
                show();
            });
        }
        
        // 开始截图
        m_pScreenshotWidget->startScreenshot();
    });
}

void DesktopTimer::toggleMute()
{
    m_bSound = !m_bSound;
    muteAction->setText(m_bSound ? "打开声音" : "静音");
    QString iconPath = m_bSound ? ":/resource/svg/Sound.svg" : ":/resource/svg/Mute.svg";
    m_pSoundBtn->setIcon(QIcon(iconPath));
    // m_bSound: true=声音打开(不静音), false=声音关闭(静音)
    // SetMute(): true=静音, false=取消静音
    // 所以需要取反：!m_bSound
    roundTimeBar->SetMute(!m_bSound);
}

void DesktopTimer::togglePin()
{
    m_bPinned = !m_bPinned;
    
    if (m_bPinned) {
        // ========== 进入"幽灵模式" ==========
        // 1. 置顶窗口并设置鼠标穿透标志
        setWindowFlags(windowFlags() | Qt::WindowStaysOnTopHint | Qt::WindowTransparentForInput);
        show();  // 修改 flags 后需要重新显示
        
        // 2. 设置窗口半透明（60% 透明度）
        setWindowOpacity(0.6);
        
        // 3. 更新按钮图标和提示
        m_pPinBtn->setIcon(QIcon(":/resource/svg/pin_active.svg"));
        m_pPinBtn->setToolTip("取消锁定（窗口已进入透明穿透模式）");
        
        // 4. 启用托盘菜单中的"解除锁定"选项和快捷键
        unlockAction->setVisible(true);
        unlockShortcut->setEnabled(true);
        
        logInfo("窗口已进入幽灵模式：置顶 + 半透明 + 鼠标穿透");
        
        // 注意：Qt::WindowTransparentForInput 会让整个窗口对鼠标事件透明
        // 包括钉住按钮，所以需要通过快捷键或托盘菜单来解除锁定
        QMessageBox::information(this, "幽灵模式", 
            "窗口已进入幽灵模式！\n\n"
            "• 窗口可见但鼠标会穿透\n"
            "• 不会阻挡任何操作\n"
            "• 右键点击托盘图标选择\"解除锁定\"来解除\n"
            "• 或按 Ctrl+Shift+L 快捷键解除",
            QMessageBox::Ok);
    } else {
        // ========== 退出"幽灵模式" ==========
        // 1. 取消置顶和鼠标穿透标志
        setWindowFlags(windowFlags() & ~Qt::WindowStaysOnTopHint & ~Qt::WindowTransparentForInput);
        show();  // 修改 flags 后需要重新显示
        
        // 2. 恢复完全不透明
        setWindowOpacity(1.0);
        
        // 3. 更新按钮图标和提示
        m_pPinBtn->setIcon(QIcon(":/resource/svg/pin.svg"));
        m_pPinBtn->setToolTip("窗口置顶");
        
        // 4. 隐藏托盘菜单中的"解除锁定"选项并禁用快捷键
        unlockAction->setVisible(false);
        unlockShortcut->setEnabled(false);
        
        logInfo("窗口已退出幽灵模式");
    }
}


void DesktopTimer::showAboutDialog()
{
    QMessageBox::about(this, "关于倒计时助手", "倒计时助手\n版本 1.0\n作者：Vere");
}

void DesktopTimer::exportData()
{
    QString fileName = QFileDialog::getSaveFileName(this, "导出数据", "", "文本文件 (*.xml)");
    if (!fileName.isEmpty())
    {
        QFile file(fileName);
        if (file.open(QIODevice::WriteOnly | QIODevice::Text))
        {
            QTextStream out(&file);
            out << "倒计时数据导出示例\n";
            out << "剩余时间：10:00\n";
            file.close();
            QMessageBox::information(this, "导出成功", "数据已成功导出到：" + fileName);
        }
        else
        {
            QMessageBox::warning(this, "导出失败", "无法写入文件：" + fileName);
        }
    }
}

void DesktopTimer::applyOpacityTransition(QWidget *widget, qreal startOpacity, qreal endOpacity, int duration)
{
    QPropertyAnimation *animation = new QPropertyAnimation(widget, "windowOpacity");
    animation->setDuration(duration);
    animation->setStartValue(startOpacity);
    animation->setEndValue(endOpacity);
    animation->setEasingCurve(QEasingCurve::OutQuad);  // 设置缓动曲线，使动画效果更平滑
    animation->start(QAbstractAnimation::DeleteWhenStopped);  // 动画完成后自动删除
}

void DesktopTimer::setScreenStyle(ScreenAction action)
{
    // 移除旧的属性
    titleWidget->setProperty("screenMode", QVariant());
    mainWidget->setProperty("screenMode", QVariant());
    lblTitle->setProperty("screenMode", QVariant());
    m_pLabel->setProperty("screenMode", QVariant());

    switch (action) {
        case ScreenAction::BlackScreen:
            applyOpacityTransition(this, 1.0, 1, 500);
            titleWidget->setProperty("screenMode", "black");
            mainWidget->setProperty("screenMode", "black");
            lblTitle->setProperty("screenMode", "black");
            m_pLabel->setProperty("screenMode", "black");
            m_pOclock->setClockColor(Qt::white);
            m_pDate->setClockColor(Qt::white);
            m_pWeekday->setClockColor(Qt::white);
            break;
        case ScreenAction::SemiTransparent:
            applyOpacityTransition(this, 1.0, 0.4, 500);
            titleWidget->setProperty("screenMode", "transparent");
            mainWidget->setProperty("screenMode", "transparent");
            lblTitle->setProperty("screenMode", "transparent");
            m_pLabel->setProperty("screenMode", "transparent");
            m_pOclock->setClockColor(Qt::white);
            m_pDate->setClockColor(Qt::white);
            m_pWeekday->setClockColor(Qt::white);
            break;
        case ScreenAction::WhiteScreen:
            applyOpacityTransition(this, 1.0, 1, 500);
            titleWidget->setProperty("screenMode", "white");
            mainWidget->setProperty("screenMode", "white");
            lblTitle->setProperty("screenMode", "white");
            m_pLabel->setProperty("screenMode", "white");
            m_pDate->setClockColor(QColor("#303030"));
            m_pOclock->setClockColor(QColor("#303030"));
            m_pWeekday->setClockColor(QColor("#303030"));
            break;
        default:
            return;
    }

    // 强制刷新样式（带动画效果）
    titleWidget->style()->unpolish(titleWidget);
    titleWidget->style()->polish(titleWidget);
    titleWidget->update();
    
    mainWidget->style()->unpolish(mainWidget);
    mainWidget->style()->polish(mainWidget);
    mainWidget->update();
    
    lblTitle->style()->unpolish(lblTitle);
    lblTitle->style()->polish(lblTitle);
    lblTitle->update();
    
    m_pLabel->style()->unpolish(m_pLabel);
    m_pLabel->style()->polish(m_pLabel);
    m_pLabel->update();
}

void DesktopTimer::connectFunction()
{
    // ✅ 连接ConfigService的配置变更信号
    connect(&ConfigService::instance(), &ConfigService::configChanged, 
            this, &DesktopTimer::updateAllData);

    connect(btnClose, &QPushButton::clicked, [this]() {
        this->close();
    });

    connect(btnMax, &QPushButton::clicked,
            [this]()
            {
                // 切换最大化/正常显示
                this->setWindowState(this->windowState().testFlag(Qt::WindowNoState) ? Qt::WindowMaximized : Qt::WindowNoState);
            });

    connect(btnMin, &QPushButton::clicked,
            [this]()
            {
                this->setWindowState((windowState() & ~Qt::WindowActive) | Qt::WindowMinimized);
            });


}

void DesktopTimer::setWindowStyle()
{
    // 获取屏幕信息并根据其尺寸设置窗口大小
    QScreen* screen = QGuiApplication::primaryScreen();
    setScreenWidth(screen->availableSize().width() * 0.2);

    setScreenHeigth(screen->availableSize().height() * 0.18);

    // [FDD-2025-03-015] 计算基础高度（不含任务面板）
    int baseHeight = m_nScreenHeigth + (m_titleTargetVisible ? TITLE_BAR_H : 0);
    m_baseWindowHeight = baseHeight;
    
    // 如果任务面板已展开，保持额外高度
    int panelHeight = (m_taskPanelExpanded && m_taskPanelHost) ? m_taskPanelHost->maximumHeight() : 0;
    int minHeight = panelHeight > 0 ? baseHeight + panelHeight : baseHeight;

    setMinimumSize(m_nScreenWidth, minHeight);
    resize(m_nScreenWidth, baseHeight + panelHeight);
}

void DesktopTimer::initMainLayout()
{
    // 圆形进度条
    roundTimeBar = createRoundTimeBar();
    mainLayout->addWidget(roundTimeBar);

    // 数字时钟
    DigitalClock* oclock = createDigitalClock();
    DateLCD* date = createDateLCD();
    WeekdayDisplay* weekday = createWeekdayDisplay();

    // "我想你了"标签
    QLabel* label = createLabel();

    // 垂直布局：包含时钟、日期和自定义文本标签
    QVBoxLayout* leftLayout = new QVBoxLayout();  // 不指定父对象，避免重复设置布局
    leftLayout->setSpacing(5);
    leftLayout->setContentsMargins(1, 1, 1, 1);

    leftLayout->addWidget(oclock);
    leftLayout->addWidget(weekday);

    // 添加包含按钮的水平布局
    QHBoxLayout* buttonLayout = createButtonLayout();
    leftLayout->addLayout(buttonLayout);

    // 添加文本标签
    leftLayout->addWidget(label);

    // 将 leftLayout 添加到主布局
    mainLayout->addLayout(leftLayout);
    mainLayout->setAlignment(Qt::AlignTop | Qt::AlignCenter);
    // mainLayout在第230行创建时已经指定了mainWidget为父对象，不需要再次setLayout
}

void DesktopTimer::refreshLayoutGeometry()
{
    if (m_mainContainer) {
        m_mainContainer->invalidate();
        m_mainContainer->activate();
    }
    if (mainWidget) {
        mainWidget->updateGeometry();
    }
    if (m_taskPanelHost) {
        m_taskPanelHost->updateGeometry();
    }
    updateGeometry();
    repaint();
}


void DesktopTimer::loadSettingsFromConfig()
{
    // ✅ 从 ConfigService 获取用户配置信息并应用到界面
    TimerConfig timerConfig = ConfigService::instance().getTimerConfig();
    TimeFormat timeFormat = ConfigService::instance().getTimeFormat();
    QFont font = ConfigService::instance().getFont();
    
    // 加载示例数据
    roundTimeBar->setRange(0, timerConfig.durationMs/1000);
    if(timeFormat == TimeFormat::HourMinuteSecond){
        font.setPointSize(font.pointSize()+m_nScreenHeigth * 0.03);
    }else if(timeFormat == TimeFormat::MinuteSecond){
        font.setPointSize(font.pointSize()+m_nScreenHeigth * 0.07);
    }else if(timeFormat == TimeFormat::Seconds){
        font.setPointSize(font.pointSize()+m_nScreenHeigth * 0.1);
    }

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    font.setWeight(QFont::DemiBold);
#else
    font.setWeight(65);
#endif
    roundTimeBar->setFont(font);
    if(timerConfig.mode == TimerMode::Countdown){
        roundTimeBar->setdefault(90,true);
        roundTimeBar->setValue(timerConfig.durationMs/1000);
    }else{
        roundTimeBar->setdefault(90,false);
        roundTimeBar->setValue(0);
    }
    roundTimeBar->setInnerDefaultTextStyle(static_cast<RoundTimeBar::InnerDefaultTextStyle>(timeFormat));

    QFont fontLabel = font;
    fontLabel.setPointSize(12);
    m_pLabel->setFont(fontLabel);

    setScreenStyle(ConfigService::instance().getTimeoutAction().screenAction);
    // 根据数据更新界面
    update();
}

RoundTimeBar* DesktopTimer::createRoundTimeBar()
{
    // ✅ 使用ConfigService获取配置
    TimerConfig timerConfig = ConfigService::instance().getTimerConfig();
    TimeFormat timeFormat = ConfigService::instance().getTimeFormat();
    QFont font = ConfigService::instance().getFont();
    
    // 创建线程和 RoundTimeBar 实例
    roundTimeBarThread = new QThread;
    roundTimeBar = new RoundTimeBar();
    // 启动线程
    roundTimeBarThread->start();
    // 注意: QWidget及其子类不能移动到其他线程，只有纯QObject才可以
    // 如果RoundTimeBar继承自QWidget，则不能调用moveToThread
    // roundTimeBar->moveToThread(roundTimeBarThread);  // 已注释，Widget必须在主线程

    roundTimeBar->setOutterBarWidth(m_nScreenHeigth * 0.115);
    roundTimeBar->setInnerBarWidth(m_nScreenHeigth * 0.115);
    roundTimeBar->setControlFlags(RoundTimeBar::all);
    roundTimeBar->setRange(0, timerConfig.durationMs/1000);
    roundTimeBar->setGifWidth(m_nScreenHeigth * 0.2);
    if(timeFormat == TimeFormat::HourMinuteSecond){
        font.setPointSize(font.pointSize()+m_nScreenHeigth * 0.03);
    }else if(timeFormat == TimeFormat::MinuteSecond){
        font.setPointSize(font.pointSize()+m_nScreenHeigth * 0.07);
    }else if(timeFormat == TimeFormat::Seconds){
        font.setPointSize(font.pointSize()+m_nScreenHeigth * 0.1);
    }

#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
    font.setWeight(QFont::DemiBold);
#else
    font.setWeight(65);
#endif
    roundTimeBar->setFont(font);
    if(timerConfig.mode == TimerMode::Countdown){
        roundTimeBar->setdefault(90,true);
        roundTimeBar->setValue(timerConfig.durationMs/1000);
    }else{
        roundTimeBar->setdefault(90,false);
        roundTimeBar->setValue(0);
    }
    roundTimeBar->setInnerDefaultTextStyle(static_cast<RoundTimeBar::InnerDefaultTextStyle>(timeFormat));
    return roundTimeBar;
}

DigitalClock *DesktopTimer::createDigitalClock()
{
    m_pOclock = new DigitalClock(this);
    m_pOclock->setClockColor(Qt::white);
    m_pOclock->setFixedSize(m_nScreenHeigth * 0.8, m_nScreenHeigth * 0.35);
    return m_pOclock;
}

DateLCD *DesktopTimer::createDateLCD()
{
    m_pDate = new DateLCD(this);
    m_pDate->setClockColor(Qt::white);
    m_pDate->setFixedSize(m_nScreenHeigth * 0.8, m_nScreenHeigth * 0.1);
    return m_pDate;
}

WeekdayDisplay *DesktopTimer::createWeekdayDisplay()
{
    m_pWeekday = new WeekdayDisplay(this);
    m_pWeekday->resize(m_nScreenHeigth * 0.8, m_nScreenHeigth * 0.1);
    QFont font;
    font.setFamily("Verdana");
    font.setPointSize(m_nScreenHeigth * 0.05);
    m_pWeekday->setFont(font);
    m_pWeekday->setHeartSize(QSize(m_nScreenHeigth * 0.05,m_nScreenHeigth * 0.05));
    m_pWeekday->setClockColor(Qt::white);
    return m_pWeekday;
}

ScrollingLabel *DesktopTimer::createLabel()
{
    m_pLabel = new ScrollingLabel(this);
    m_pLabel->setObjectName("mainScrollingLabel");
    
    // 使用QuoteService获取初始语录
    QString initialQuote = QuoteService::instance().getCurrentQuote();
    m_pLabel->setScrollText(initialQuote);
    
    m_pLabel->setScrollType(ScrollingLabel::LeftToRight);
    m_pLabel->setMinimumWidth(m_nScreenHeigth * 0.8);
    m_pLabel->setScrollSpeed(10);
    m_pLabel->startScrolling();
    m_pLabel->setFixedHeight(m_nScreenHeigth * 0.1);
    m_pLabel->setAlignment(Qt::AlignCenter);
    
    // 连接语录更换信号
    connect(&QuoteService::instance(), &QuoteService::quoteChanged,
            this, [this](const QString& newQuote) {
        m_pLabel->setScrollText(newQuote);
        m_pLabel->startScrolling();  // 重新开始滚动
        logDebug("滚动标签语录已更新: " << newQuote);
    });
    
    // 启动自动更换语录（每30分钟）
    QuoteService::instance().startAutoChange(30);
    
    return m_pLabel;
}

QHBoxLayout *DesktopTimer::createButtonLayout()
{
    QHBoxLayout* hLayout = new QHBoxLayout();  // 不指定父对象，避免重复设置布局
    hLayout->setSpacing(10);  // 日期和按钮之间的间距
    hLayout->setContentsMargins(5, 0, 5, 0);  // 左右各留5px边距
    
    // ========== 左侧：日期显示 ==========
    // 日期单独占用固定空间，不被挤压
    m_pDate->setFixedSize(m_nScreenHeigth * 0.4, m_nScreenHeigth * 0.1);  // 固定大小
    m_pDate->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);  // 固定尺寸策略
    hLayout->addWidget(m_pDate, 0, Qt::AlignLeft | Qt::AlignVCenter);
    
    // 添加弹性空间，日期和按钮之间自动调整
    hLayout->addStretch(1);

    // ========== 右侧：按钮组 ==========
    QSize btnSize(m_nScreenHeigth*0.05, m_nScreenHeigth*0.05);  // 再减小按钮
    
    // 创建按钮容器，更好地控制按钮布局
    QWidget* btnContainer = new QWidget();
    QHBoxLayout* btnLayout = new QHBoxLayout(btnContainer);
    btnLayout->setSpacing(6);  // 按钮之间间距减小到6px
    btnLayout->setContentsMargins(0, 0, 0, 0);
    
    // 添加声音按钮
    m_pSoundBtn = createButton(":/resource/svg/Sound.svg", btnSize);
    m_pSoundBtn->setToolTip("声音");
    m_pSoundBtn->setFixedSize(btnSize);  // 固定按钮大小
    connect(m_pSoundBtn, &QPushButton::clicked, this, &DesktopTimer::toggleMute);
    btnLayout->addWidget(m_pSoundBtn);

    // 添加钉住按钮
    m_pPinBtn = createButton(":/resource/svg/pin.svg", btnSize);
    m_pPinBtn->setToolTip("窗口置顶");
    m_pPinBtn->setFixedSize(btnSize);  // 固定按钮大小
    connect(m_pPinBtn, &QPushButton::clicked, this, &DesktopTimer::togglePin);
    btnLayout->addWidget(m_pPinBtn);

    // 添加日计划按钮
    m_pPlanBtn = createButton(":/resource/svg/note_white.svg", btnSize);
    m_pPlanBtn->setToolTip("日计划");
    m_pPlanBtn->setFixedSize(btnSize);  // 固定按钮大小
    connect(m_pPlanBtn, &QPushButton::clicked, this, &DesktopTimer::openPlan);
    btnLayout->addWidget(m_pPlanBtn);

    // 添加截图按钮
    m_pScreenshotBtn = createButton(":/resource/svg/screen_white.svg", btnSize);
    m_pScreenshotBtn->setToolTip("截图");
    m_pScreenshotBtn->setFixedSize(btnSize);  // 固定按钮大小
    connect(m_pScreenshotBtn, &QPushButton::clicked, this, &DesktopTimer::startScreenshot);
    btnLayout->addWidget(m_pScreenshotBtn);

    // 添加设置按钮
    m_pSettingBtn = createButton(":/resource/svg/setting.svg", btnSize);
    m_pSettingBtn->setToolTip("设置");
    m_pSettingBtn->setFixedSize(btnSize);  // 固定按钮大小
    connect(m_pSettingBtn, &QPushButton::clicked, this, &DesktopTimer::openSettings);
    btnLayout->addWidget(m_pSettingBtn);

    // [FDD-2025-03-015][AC-001] 添加任务面板切换按钮
    m_pTaskPanelBtn = createButton(":/resource/svg/left_white.svg", btnSize);
    m_pTaskPanelBtn->setToolTip(tr("任务面板 (Alt+T)"));
    m_pTaskPanelBtn->setFixedSize(btnSize);
    connect(m_pTaskPanelBtn, &QPushButton::clicked, this, &DesktopTimer::onTaskPanelToggle);
    btnLayout->addWidget(m_pTaskPanelBtn);
    
    // 创建 Alt+T 快捷键
    m_taskPanelShortcut = new QShortcut(QKeySequence(Qt::ALT | Qt::Key_T), this);
    connect(m_taskPanelShortcut, &QShortcut::activated, this, &DesktopTimer::onTaskPanelToggle);
    
    // 设置按钮容器的固定大小，防止挤压日期（6个按钮：声音、钉住、日计划、截图、设置、任务面板）
    btnContainer->setFixedSize((btnSize.width() + 6) * 6 - 6, btnSize.height());
    
    // 将按钮容器添加到主布局
    hLayout->addWidget(btnContainer, 0, Qt::AlignRight | Qt::AlignVCenter);

    return hLayout;
}

QPushButton *DesktopTimer::createButton(const QString &iconPath, const QSize &iconSize)
{
    QPushButton* button = new QPushButton(this);
    button->setObjectName("mainActionButton");
    button->setText("");
    button->setIcon(QIcon(iconPath));
    button->setIconSize(iconSize);
    button->setCursor(QCursor(Qt::PointingHandCursor));
    button->resize(m_nScreenHeigth*0.07, m_nScreenHeigth*0.07);
    return button;
}


void DesktopTimer::updateAllData()
{
    // 重新从配置加载数据
    loadSettingsFromConfig();
}

void DesktopTimer::applyStyles()
{
    // 从QSS文件加载样式
    QString style = StyleLoader::loadDarkTheme();
    if (!style.isEmpty()) {
        setStyleSheet(style);
    } else {
        qWarning() << "警告：主窗口样式文件加载失败！请检查 resource.qrc 配置。";
    }
}

// ========== [FDD-2025-03-015] Task Panel Methods ==========

/**
 * @brief [AC-001][AC-002] 任务面板切换响应（按钮点击或快捷键）
 */
void DesktopTimer::onTaskPanelToggle()
{
    // [R-002-DUP] 状态机检查：防止动画进行中重复触发
    if (m_panelAnimation && m_panelAnimation->state() == QAbstractAnimation::Running) {
        qWarning() << "[E001_ANIMATION_RUNNING] Animation in progress, ignoring toggle";
        return;
    }
    
    // [R-002-DUP] 防抖检查 (200ms)
    qint64 now = QDateTime::currentMSecsSinceEpoch();
    if (now - m_lastToggleTs < 200) {
        qDebug() << "[DEBOUNCE] Toggle too fast, ignoring";
        return;
    }
    m_lastToggleTs = now;
    
    // 切换状态
    toggleTaskPanel(!m_taskPanelExpanded);
}

/**
 * @brief [API-001][AC-001][AC-002] 执行面板展开/收缩动画
 * @param expanded true=展开，false=收缩
 */
void DesktopTimer::toggleTaskPanel(bool expanded)
{
    if (!m_taskPanelHost || !m_panelAnimation) {
        qWarning() << "[TaskPanel] Panel not initialized, skipping toggle";
        return;
    }
    
    // [FDD-2025-03-015][UX] 计算面板目标高度：最多显示5条任务
    const int TASK_ITEM_HEIGHT_COMPACT = 32;   // 紧凑模式任务固定高度
    const int MAX_VISIBLE_TASKS = 5;           // 最多显示5条
    const int QUICK_ADD_HEIGHT_COMPACT = 28;   // 紧凑模式快速添加栏高度
    const int CONTENT_MARGINS_COMPACT = 8;     // 紧凑模式上下边距 (4px * 2)
    const int CONTENT_SPACING_COMPACT = 4;     // 快速添加栏和任务列表之间的间距

    int taskListHeight = TASK_ITEM_HEIGHT_COMPACT * MAX_VISIBLE_TASKS;
    int panelTargetHeight = expanded ? (CONTENT_MARGINS_COMPACT + QUICK_ADD_HEIGHT_COMPACT + CONTENT_SPACING_COMPACT + taskListHeight) : 0;
    
    // 计算窗口目标高度：基础高度 + 面板高度
    int baseHeight = m_nScreenHeigth + (m_titleTargetVisible ? TITLE_BAR_H : 0);
    int windowTargetHeight = baseHeight + panelTargetHeight;
    
    // 1. 启动面板高度动画
    m_panelAnimation->stop();
    m_panelAnimation->setStartValue(m_taskPanelHost->maximumHeight());
    m_panelAnimation->setEndValue(panelTargetHeight);
    if (expanded && !m_taskPanelHost->isVisible()) {
        m_taskPanelHost->setVisible(true);
    }
    m_panelAnimation->start();
    
    // 2. 直接调整窗口高度，保持原有布局尺寸
    setMinimumHeight(expanded ? windowTargetHeight : baseHeight);
    resize(width(), windowTargetHeight);
    refreshLayoutGeometry();
    
    m_taskPanelExpanded = expanded;
    
    // 立即刷新任务列表（若展开）
    if (expanded && m_embeddedPlanWidget) {
        m_embeddedPlanWidget->refreshTasks();
    }
}

/**
 * @brief [AC-001][AC-002] 动画完成回调 - 切换图标并持久化状态
 */
void DesktopTimer::onPanelAnimationFinished()
{
    if (!m_pTaskPanelBtn) return;
    
    // 切换按钮图标
    QString iconPath = m_taskPanelExpanded ? 
        ":/resource/svg/up.svg" : ":/resource/svg/left_white.svg";
    
    m_pTaskPanelBtn->setIcon(QIcon(iconPath));
    
    if (m_taskPanelHost && !m_taskPanelExpanded) {
        m_taskPanelHost->setVisible(false);
        m_taskPanelHost->setMaximumHeight(0);
        setMinimumHeight(m_baseWindowHeight);
        resize(width(), m_baseWindowHeight);
    }
    
    refreshLayoutGeometry();
    
    // [AC-002] 持久化状态
    if (m_taskPanelCtrl) {
        m_taskPanelCtrl->persistState(m_taskPanelExpanded);
    }

    qDebug() << "[TaskPanel] Animation finished, state persisted:" << m_taskPanelExpanded;
}

// ========== [FDD-2025-03-021] WindowRegistry Methods ==========

/**
 * @brief [API-001] 单例窗口管理：复用已存在的窗口或创建新窗口
 * @param key 窗口唯一标识符（如 "settings", "plan"）
 * @param factory 窗口创建函数
 * @return 复用或新建的窗口指针
 */
QWidget* DesktopTimer::showSingletonWindow(const QString& key, std::function<QWidget*()> factory)
{
    if (!factory) {
        qWarning() << "[WindowRegistry][E001_FactoryNull] Factory function is null for key:" << key;
        return nullptr;
    }

    // 检查注册表中是否已存在
    if (m_windowRegistry.contains(key)) {
        WindowRegistryEntry& entry = m_windowRegistry[key];

        // 如果窗口仍然有效，复用它
        if (entry.widget) {
            qDebug() << "[WindowRegistry] Reusing existing window:" << key;
            entry.widget->show();
            entry.widget->raise();
            entry.widget->activateWindow();
            return entry.widget.data();
        } else {
            // 窗口已销毁但记录还在，清理记录
            qDebug() << "[WindowRegistry] Cleaning up stale entry:" << key;
            m_windowRegistry.remove(key);
        }
    }

    // 创建新窗口
    qDebug() << "[WindowRegistry] Creating new window:" << key;
    QWidget* newWindow = factory();
    if (!newWindow) {
        qWarning() << "[WindowRegistry] Factory returned null for key:" << key;
        return nullptr;
    }

    // 设置 Qt::WA_DeleteOnClose 属性，确保窗口关闭时自动删除
    newWindow->setAttribute(Qt::WA_DeleteOnClose);

    // 注册到 WindowRegistry
    WindowRegistryEntry entry;
    entry.key = key;
    entry.widget = newWindow;
    entry.factory = factory;
    m_windowRegistry[key] = entry;

    // 连接 destroyed 信号，自动清理注册表
    connect(newWindow, &QObject::destroyed, this, &DesktopTimer::onWindowDestroyed);

    // 添加到 CAppSingleton（保持兼容性）
    CAppSingleton<QWidget>::GetInstance()->AddObject(newWindow);

    // 显示窗口
    newWindow->show();

    qDebug() << "[WindowRegistry] Window registered and shown:" << key
             << "Total registered:" << m_windowRegistry.size();

    return newWindow;
}

/**
 * @brief [API-001] 窗口销毁时的清理槽函数
 * @param obj 被销毁的窗口对象
 */
void DesktopTimer::onWindowDestroyed(QObject* obj)
{
    if (!obj) return;

    // 从 CAppSingleton 中移除
    QWidget* widget = qobject_cast<QWidget*>(obj);
    if (widget) {
        CAppSingleton<QWidget>::GetInstance()->RemoveObject(widget);
    }

    // 从 WindowRegistry 中查找并移除
    for (auto it = m_windowRegistry.begin(); it != m_windowRegistry.end(); ) {
        if (it.value().widget.data() == obj || it.value().widget.isNull()) {
            qDebug() << "[WindowRegistry] Removing destroyed window:" << it.key();
            it = m_windowRegistry.erase(it);
        } else {
            ++it;
        }
    }

    qDebug() << "[WindowRegistry] Cleanup complete. Remaining windows:" << m_windowRegistry.size();
}

